package com.health.work.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

public class WebServiceUtils {
	private static final String NAMESPACE = "http://WebXml.com.cn/";// WebService地址
	private static String URL = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
	private static final String METHOD_NAME = "getWeatherbyCityName";
	private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";//NAMESPACE+METHOD_NAME
	private String weatherToday;
	private SoapObject detail;

	public void getWeather(String cityName) {
		try {
			SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
			System.out.println("rpc" + rpc);
			System.out.println("cityName is " + cityName);
			rpc.addProperty("theCityName", cityName);

			
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(URL);

			ht.debug = true;

			ht.call(SOAP_ACTION, envelope);
			System.out.println(envelope.getResponse().toString());
			detail =(SoapObject) envelope.getResponse();
			
			System.out.println("detail" + detail);
			parseWeather(detail);

			return;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void parseWeather(SoapObject detail)
			throws UnsupportedEncodingException {
		String date = detail.getProperty(6).toString();
		weatherToday = "今天：" + date.split("")[0];
		weatherToday = weatherToday + "\n天气：" + date.split("")[1];
		weatherToday = weatherToday + "\n气温："
				+ detail.getProperty(5).toString();
		weatherToday = weatherToday + "\n风力："
				+ detail.getProperty(7).toString() + "\n";
		System.out.println("weatherToday is " + weatherToday);
	}
	
	
	public DefaultJSONData sendRequest(SoapObject rpc,String action,String url,DefaultJSONData jsonData) {
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(url);

			ht.debug = true;
			Log.e("WebServiceUtils", HEALTHPASSPORT.NAMESPACE+action);
			ht.call(HEALTHPASSPORT.NAMESPACE+action, envelope);
		
			System.out.println(envelope.getResponse().toString());
			
			String buffData = envelope.getResponse().toString();
			if (buffData.startsWith("{")) {
				JSONObject object = new JSONObject(buffData);
				jsonData.parse(object);
			} else if (buffData.startsWith("[")) {
				JSONArray object = new JSONArray(buffData);
				jsonData.parse(object);
			} else {
				jsonData.parse(buffData);
			}

		} catch (Exception e) {
			e.printStackTrace();
			try {
				jsonData.parse("9999");
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
		}
		return jsonData;
	}
	
	
	//上传图片相关demo
	public void testUpload(){  
        try{  
            String srcUrl = "/sdcard/"; //路径  
            String fileName = "aa.jpg";  //文件名  
            FileInputStream fis = new FileInputStream(srcUrl + fileName);  
            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            byte[] buffer = new byte[1024];  
            int count = 0;  
            while((count = fis.read(buffer)) >= 0){  
                baos.write(buffer, 0, count);  
            }  
            String uploadBuffer = new String(Base64.encode(baos.toByteArray()));  //进行Base64编码  
            String methodName = "uploadImage";  
            connectWebService(methodName,fileName, uploadBuffer);   //调用webservice  
            Log.i("connectWebService", "start");  
            fis.close();  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    } 
	
	
	//使用 ksoap2 调用webservice   
    private boolean connectWebService(String methodName,String fileName, String imageBuffer) {  
        String namespace = "http://134.192.44.105:8080/SSH2/service/IService";  // 命名空间，即服务器端得接口，注：后缀没加 .wsdl，  
                                                                                //服务器端我是用x-fire实现webservice接口的  
        String url = "http://134.192.44.105:8080/SSH2/service/IService";   //对应的url  
        url=HEALTHPASSPORT.URL_PIC;
        namespace=HEALTHPASSPORT.NAMESPACE;
        //以下就是 调用过程了，不明白的话 请看相关webservice文档     
        SoapObject soapObject = new SoapObject(namespace, methodName);      
        soapObject.addProperty("filename", fileName);  //参数1   图片名  
        soapObject.addProperty("image", imageBuffer);   //参数2  图片字符串  
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
                SoapEnvelope.VER10);  
        envelope.dotNet = false;  
        envelope.setOutputSoapObject(soapObject);  
        HttpTransportSE httpTranstation = new HttpTransportSE(url);  
        try {  
            httpTranstation.call(namespace, envelope);  
            Object result = envelope.getResponse();  
            Log.i("connectWebService", result.toString());  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return false;  
    } 
    
    /**
     * 上传图片
     * @param pics
     * @return
     */
     public static String UploadPicture(String pics ) {
         String str_result = "";
         SoapObject request = new SoapObject(HEALTHPASSPORT.NAMESPACE,"UploadPicture");
         request.addProperty("type","uploadimg" );
         request.addProperty("file",pics );
         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                 SoapEnvelope.VER11);
         envelope.bodyOut = request;
         envelope.dotNet = false;
         envelope.setOutputSoapObject(request);
         HttpTransportSE ht = new HttpTransportSE(HEALTHPASSPORT.URL_PIC);
         ht.debug = true;
         try {
             ht.call(HEALTHPASSPORT.NAMESPACE+"UploadPicture", envelope);
             Object  result = (Object) envelope.getResponse();
             String str_res = result.toString();
             Log.d("guojie", "envelope.getResponse() =="+result.toString());
             str_result=str_res;
             Log.d("guojie", "UploadPicture ===="+str_result);
         } catch (IOException e) {
             e.printStackTrace();
         } catch (XmlPullParserException e) {
             e.printStackTrace();
         } catch(Exception e) {
             e.printStackTrace();
         }
         return str_result;
     }

}
